package com.demo.model;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class Theme {
    static Color BOARD_BACKGROUND;
    static Color BLANK_BACKGROUND;
    static Map<String, String> CARD_COLORS = new HashMap<>();

    static {
        try {
            init("/theme/theme.xml");
        } catch (ParserConfigurationException | IOException | SAXException e) {
            e.printStackTrace();
        }
    }

    public static void init(String xmlPath) throws ParserConfigurationException, IOException, SAXException {
        InputStream resourceAsStream = Theme.class.getResourceAsStream(xmlPath);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();
        Document document = db.parse(resourceAsStream);

        NodeList colors = ((Element) document.getElementsByTagName("card").item(0)).getElementsByTagName("color");
        for (int i = 0; i < colors.getLength(); ++i) {
            Element e = (Element) colors.item(i);
            String type = e.getAttribute("type");
            String color = e.getTextContent().toUpperCase();
            CARD_COLORS.put(type, color);
        }

        NodeList boardColor = ((Element) document.getElementsByTagName("board").item(0)).getElementsByTagName("color");
        for (int i = 0; i < boardColor.getLength(); ++i) {
            Element e = (Element) boardColor.item(i);
            String type = e.getAttribute("type");
            String color = e.getTextContent().toUpperCase();
            if (type.equals("background")) {
                BOARD_BACKGROUND = Color.decode(color);
            } else if (type.equals("blank")) {
                BLANK_BACKGROUND = Color.decode(color);
            }
        }
    }

    public static Color getCardColor(int number) {
        String key = String.valueOf(number);
        String value = CARD_COLORS.getOrDefault(key, CARD_COLORS.get("2"));
        return Color.decode(value);
    }

    public static Color getShadowColor() {
        String value = CARD_COLORS.get("shadow");
        return Color.decode(value);
    }

    public static Color getBoardBackground() {
        return BOARD_BACKGROUND;
    }

    public static Color getBlankBackground() {
        return BLANK_BACKGROUND;
    }
}
